package com.joysuch.wwyt.core.common.util;

import com.google.gson.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * gson工具类
 *
 * @author qingzhou
 * 2019-07-08
 */
public class JsonUtil {

    private static final AtomicLong COUNT = new AtomicLong(0);
    private static final int GSON_SIZE = 16;
    private static final Gson[] GSONS = new Gson[GSON_SIZE];
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    static {
        for (int i = 0; i < GSON_SIZE; i++) {
            GSONS[i] = new GsonBuilder()
                    .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(dtf)))
                    .registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) -> {
                        String asString = json.getAsString();
                        return LocalDateTime.parse(asString, dtf);
                    }).create();
        }
    }

    public static String toJson(Object o) {
        if (o == null) {
            return "null";
        }
        int idx = randomIdx();
        return GSONS[idx].toJson(o);
    }

    public static <T> T fromJson(String json, Class<T> clazz) throws JsonSyntaxException {
        int idx = randomIdx();
        return GSONS[idx].fromJson(json, clazz);
    }

    public static <T> List<T> fromListJson(String json, Class<T> clazz) throws JsonSyntaxException {
        JsonParser parser = new JsonParser();
        JsonArray array = parser.parse(json).getAsJsonArray();
        int idx = randomIdx();
        List<T> ls = new ArrayList<T>();
        for (final JsonElement js : array) {
            T entity = GSONS[idx].fromJson(js, clazz);
            ls.add(entity);
        }
        return ls;
    }

    private static int randomIdx() {
        long andIncrement = COUNT.getAndIncrement();
        return (int) (andIncrement % GSON_SIZE);
    }
}
